import {
  Body,
  Controller,
  Get,
  Post,
  Query,
  BadRequestException,
} from '@nestjs/common'
import { CurrentUser } from 'src/common/decorator/user.decorator'
import { categoryProduct } from 'src/entities/categoryProduct.entity'
import { ProductEntity } from 'src/entities/product.entity'
import { ProductSkuEntity } from 'src/entities/productSkuEntity.entity'
import { UserEntity } from 'src/entities/user.entity'
import { NoAuth } from 'src/utils/noAuth'
import { changeResultToString, filterObject } from 'src/utils/utils'
import { Param } from '_@nestjs_common@7.6.18@@nestjs/common'
import {
  ApiBearerAuth,
  ApiOperation,
  ApiTags,
  ApiQuery,
  ApiParam,
  ApiBody,
} from '_@nestjs_swagger@4.8.0@@nestjs/swagger'
import { isArray } from '_class-validator@0.12.2@class-validator'
import {
  addUserSkuDto,
  createCategoryProductDto,
  createProductDto,
} from './dto/product.dto'
import { queryProductDto } from './dto/query-product.dto'
import { ProductService } from './product.service'

@Controller('product')
@ApiTags('商品')
export class ProductController {
  constructor(private readonly ProductService: ProductService) {}

  @Post('/create')
  @ApiOperation({ summary: '创建商品' })
  @ApiBearerAuth()
  async createProduct(@Body() body: createProductDto) {
    const [err, product] = await this.ProductService.create(body)
    if (err) {
      return err
    } else {
      return product
    }
  }

  @Get('/get/:id')
  @ApiOperation({ summary: '获取商品简介' })
  @ApiParam({
    name: 'id',
    required: true,
    type: 'number',
  })
  @NoAuth()
  async getProduct(@Param('id') id) {
    const [err, product] = await this.ProductService.getOne(id)
    if (err) {
      return err
    } else {
      return product
    }
  }

  @Get('/getProductType')
  @ApiOperation({ summary: '获取商品类型' })
  @NoAuth()
  async getProductType() {
    const [err, productTypes] = await this.ProductService.getType()
    if (err) {
      return err
    } else {
      return productTypes
    }
  }

  @Post('/addMultiProduct')
  @ApiOperation({ summary: '批量插入创建商品' })
  @NoAuth()
  async addMultiProduct(@Body() body: Array<any>) {
    const filterArr = body.filter(
      i =>
        i.view_type == 'list_eight_product_tab' ||
        i.view_type == 'list_eight_product',
    )

    let arr = []
    filterArr.forEach(item => {
      // 单数据
      if (item.view_type === 'list_eight_product') {
        arr = arr.concat(
          item.body.product_list.map(product => {
            return {
              ...product,
              tab_name: item.body.floor_name,
            }
          }),
        )
      } else {
        // tab数据
        item.body.tab_content.forEach(tab => {
          if ((tab.tab_name = '热门')) tab.tab_name = item.body.floor_name
          arr = arr.concat(
            tab.product_list.map(product => {
              return {
                ...product,
                tab_name: tab.tab_name,
              }
            }),
          )
        })
      }
    })

    const addList: Array<ProductEntity> = filterObject(
      arr.map(
        (item): ProductEntity => {
          item.id = item.product_id
          item.name = item.product_name
          item.brief = item.product_brief
          item.price = item.product_price
          item.org_price = item.product_org_price
          return item
        },
      ),
    )
    const [err, msg] = await this.ProductService.add(addList)
    if (err) {
      return err
    } else {
      return msg
    }
  }

  @Get('/getProductList')
  @ApiOperation({ summary: '获取商品列表' })
  @NoAuth()
  async getProductList(@Query() query: queryProductDto) {
    const [err, productPagination] = await this.ProductService.getList(query)
    if (err) {
      return err
    } else {
      return productPagination
    }
  }

  @Post('/addMultiCategoryProduct')
  @ApiOperation({ summary: '批量插入分类及商品' })
  @NoAuth()
  async addCategoryProduct(@Body() body: Array<any>) {
    let arr: Array<createCategoryProductDto> = []
    body.forEach(typeItem => {
      typeItem.category_list.forEach(productList => {
        if (productList.view_type === 'category_group') {
          productList.body.items.forEach(product => {
            arr.push({
              category_name: product.category_name,
              product_name: product.product_name,
              img_url: product.img_url,
              img_url_webp: product.img_url_webp,
              type_name: typeItem.category_name,
              action_type: product.action.type,
              action_path: product.action.path,
            })
          })
        }
      })
    })

    const [
      err,
      insertResult,
    ] = await this.ProductService.addCategoryProductList(arr)
    if (err) {
      return err
    } else {
      return changeResultToString(insertResult).msg
    }
  }

  @Get('/getMultiCategoryProduct')
  @ApiOperation({ summary: '批量获取分类及商品' })
  @NoAuth()
  async getCategoryProduct() {
    const [err, result] = await this.ProductService.getCategoryProductList()
    if (err) {
      return err
    }
    function initObjArray(obj, key): Array<any> {
      if (!isArray(obj[key])) {
        obj[key] = []
      }
      return obj[key]
    }
    let typeObj = {
        // 'Redmi手机':['Redmi红米 Note系列']
      },
      cateObj = {
        // Redmi红米 Note系列:[{id}]
      }
    result.forEach(item => {
      let typeTar = initObjArray(typeObj, item.type_name)
      let cateTar = initObjArray(cateObj, item.category_name)
      if (!typeTar.includes(item.category_name)) {
        typeTar.push(item.category_name)
      }

      cateTar.push(item)

      Reflect.deleteProperty(item, 'id')
      Reflect.deleteProperty(item, 'created_at')
      Reflect.deleteProperty(item, 'update_at')
      Reflect.deleteProperty(item, 'type_name')
      Reflect.deleteProperty(item, 'category_name')
    })

    let res = Object.keys(typeObj).map(type_name => {
      return {
        title: type_name,
        categoryList: typeObj[type_name].map(cateName => {
          return {
            categoryName: cateName,
            productList: cateObj[cateName],
          }
        }),
      }
    })

    if (err) {
      return err
    } else {
      return res
    }
  }

  @Get('/getProductSkuList/:id')
  @ApiOperation({ summary: '商品信息及sku列表' })
  @NoAuth()
  @ApiParam({
    name: 'id',
    type: 'number',
    required: true,
  })
  async getProductSkuList(@Param('id') id) {
    const [err, result] = await this.ProductService.getProductSkuData(id)
    if (err) {
      return err
    }

    let sku_id_map = {
        // 分类id:[规格A ID, 规格B ID]
      },
      sku_kv_map = {
        // k${id}:name k|分类
        // v${id}:name v|规格
      },
      sku_stock_map = {
        // v${id}v${id}:sku
      }
    // 增加分类到sku_kv_map
    result.categoryList.forEach(category => {
      sku_kv_map['k' + category.id] = category.name
      sku_id_map[category.id] = category.categoryValue.map(i => i.id)
      category.categoryValue.forEach(item => {
        sku_kv_map['v' + item.id] = item.name
      })
    })

    result.product.productSku.forEach(sku => {
      sku_stock_map['v' + sku.v_ids.replace(/,/g, 'v')] = sku
    })

    return {
      product: result.product,
      sku: {
        sku_id_map,
        sku_kv_map,
        sku_stock_map,
      },
    }
  }

  @Post('/editUserSku')
  @ApiOperation({ summary: '创建编辑用户购物车sku' })
  @ApiBearerAuth()
  async editUserSku(
    @CurrentUser() user: UserEntity,
    @Body() body: addUserSkuDto,
  ) {
    const result = await this.ProductService.editSkuToUser(body, user)
    return result
  }

  @Get('/getUserSku')
  @ApiOperation({ summary: '获取用户购物车' })
  @ApiBearerAuth()
  async getUserSku(@CurrentUser() user: UserEntity) {
    const result = await this.ProductService.getUserSku(user)
    return result
  }

  @Post('/deleteUserSku')
  @ApiOperation({ summary: '删除用户购物车' })
  @ApiBearerAuth()
  @ApiBody({
    isArray: true,
    description: 'id列表',
  })
  async delelteUserSku(
    @CurrentUser() user: UserEntity,
    @Body() body: Array<number>,
  ) {
    const result = await this.ProductService.deleteUserSku(user, body)
    return result
  }
}
